<?php

namespace app\common\logic;

use app\common\model\Order;
use app\common\model\TeamFollow;
use app\common\model\TeamFound;
use think\Db;
use think\Model;

/**
 * 拼团订单逻辑类
 */
class TeamOrderLogic extends Model
{
    protected $team;// 拼团模型
    protected $order;//订单模型
    protected $goods;//商品模型
    protected $goodsBuyNum;//购买的商品数量
    protected $user_id = 0;//user_id
    protected $teamFound;//开团模型

    public function __construct()
    {
        parent::__construct();

    }

    /**
     * 设置用户ID
     * @param $user_id
     */
    public function setUserId($user_id)
    {
        $this->user_id = $user_id;
    }

    /**
     * 设置拼团模型
     * @param $team
     */
    public function setTeam($team)
    {
        $this->team = $team;
    }

    /**
     * 设置商品模型
     * @param $goods
     */
    public function setGoods($goods)
    {
        $this->goods = $goods;
    }

    /**
     * 设置订单模型
     * @param $order
     */
    public function setOrder($order)
    {
        $this->order = $order;
    }

    /**
     * 设置购买的商品数量
     * @param $goodsBuyNum
     */
    public function setGoodsBuyNum($goodsBuyNum)
    {
        $this->goodsBuyNum = $goodsBuyNum;
    }

    /**
     * 设置开团模型
     * @param $teamFound
     */
    public function setTeamFound($teamFound){
        $this->teamFound = $teamFound;
    }


    /**
     * 下单后付款前调用
     */
    public function afterAddOrder(){

        $user = Db::name('user')->field('nickname,avatar')->where('id', $this->user_id)->find();

        if($this->teamFound){
            /**团员拼团s**/
            $team_follow_data = [
                'follow_user_id' => $this->user_id,
                'follow_user_nickname' => $user['nickname'],
                'follow_user_avatar' => $user['avatar'],
                'follow_time' => time(),
                'order_id' => $this->order->id,
                'found_id' => $this->teamFound['id'],
                'found_user_id' => $this->teamFound['user_id'],
                'team_id' => $this->team['id'],
            ];
            $result = Db::name('team_follow')->insert($team_follow_data);
            if($result){

                return ['code' => 1, 'msg' => '', 'data'=> ['found_id' =>  $this->teamFound['id']]];
            }else{
                return ['code' => 0, 'msg' => '写入拼团表失败', 'data'=> ''];
            }
            /***团员拼团e***/
        }else{
            /***团长开团s***/

            //是否参与过拼团

            $team_found_data = [
                'found_time'=>time(),
                'found_end_time' => (intval(time()) + intval($this->team['time_limit'])),
                'user_id' => $this->user_id,
                'team_id' => $this->team['id'],
                'nickname' => $user['nickname'],
                'avatar' => $user['avatar'],
                'order_id' => $this->order->id,
                'need' => $this->team['needer'],
                'price'=> $this->team['team_price'],
                'goods_price' => $this->goods->shop_price,

            ];
            $result = Db::name('team_found')->insert($team_found_data);
            if($result){
                $found_id = Db::name('team_follow')->getLastInsID();
                return ['code' => 1, 'msg' => '', 'data'=> ['found_id' => $found_id]];
            }else{
                return ['code' => 0, 'msg' => '写入开团表失败', 'data'=> ''];
            }
            /***团长开团e***/
        }
    }

    /**
     * 拼团活动是否能下单
     */
    public function teamIsCanAddOrder(){
        if (empty($this->team) || $this->team['status'] != 1) {
            return ['code' => 0, 'msg' => '该商品拼团活动不存在或者已下架', 'data' => ''];
        }

        if (empty($this->goods)) {
            return ['code' => 0, 'msg' => '该商品拼团活动不存在或者已下架', 'data' => ''];
        }

        if ($this->goodsBuyNum <= 0) {
            return ['code' => 0, 'msg' => '至少购买一份', 'data' => ''];
        }
        if ($this->goodsBuyNum > $this->team['buy_limit']) {
            return ['code' => 0, 'msg' => '购买数已超过该活动单次购买限制数(' . $this->team['buy_limit'] . ')', 'data' => ''];
        }

        return ['code' => 1, 'msg' => '', 'data' => ''];

    }

    /**
     * 更改订单商品购买商品数
     * @param $goodsNum
     */
    public function changeNum($goodsNum)
    {
        if ($goodsNum != $this->orderGoods['goods_num']) {
            $this->orderGoods->goods_num = $goodsNum;
            $this->order->goods_price = $this->orderGoods->member_goods_price * $goodsNum;
            $this->order->order_amount = $this->orderGoods->member_goods_price * $goodsNum;
            $this->order->total_amount = $this->orderGoods->member_goods_price * $goodsNum;
        }
    }

    /**
     * 返回订单模型
     * @return mixed
     */
    public function getOrder()
    {
        return $this->order;
    }

    /**
     * 拼团支付后操作
     * @param $order
     * @throws \think\Exception
     */
    public function doOrderPayAfter($order){
        $teamFound = TeamFound::get(['order_id' => $order['id']]);
        //团长的单
        if ($teamFound) {
            //有bug屏蔽掉
//            $teamFound->found_time = time();
//            $teamFound->found_end_time = (intval(time()) + intval($this->team['time_limit']));
            $teamFound->status = 1;
            $teamFound->save();
        }else{
            //团员的单
            $teamFollow = TeamFollow::get(['order_id' => $order['id']]);
            if($teamFollow){
                $teamFollow->status = 1;
                $teamFollow->save();
                //更新团长的单
                $teamFollow->team_found->join = $teamFollow['team_found']['join'] + 1;//参团人数+1
                //如果参团人数满足成团条件
                if($teamFollow->team_found->join >= $teamFollow->team_found->need){
                    $teamFollow->team_found->status = 2;//团长成团成功
                    //更新团员成团成功
                    Db::name('team_follow')->where(['found_id'=>$teamFollow->team_found->id,'status'=>1])->update(['status'=>2]);
                }
                $teamFollow->team_found->save();
            }
        }
    }

    /**
     * 成团失败退款
     */
    public function refundTeamOrder(){
        Db::name('test')->insert(['content' => 'refundTeamOrder']);

        if($this->order->pay_status == 1){
            //退团长的单
            $this->order->pay_status = 3;
            $this->order->user_note = '成团失败，退回' . $this->order['total_amount'] . '元';
            $this->order->save();

            //余额记录
            $memo = '成团失败，退回' . $this->order['total_amount'] . '元';
            change_user_account_log($this->user_id, $this->order['total_amount'], $memo, $this->order['order_sn'], $this->order['id']);
            //写入资金记录表
            change_expense($this->order['total_amount'],$this->order['id']);

            //退团员的单
            $teamFollow = Db::name('team_follow')->where(['found_id' => $this->teamFound['id']])->select();
            if($teamFollow){

                foreach($teamFollow as $k => $v){

                    Db::name('team_follow')->where(['id' => $v['id']])->update(['status' => 3]);

                    $order = Db::name('order')->find($v['order_id']);
                    $user_note = '成团失败，退回' . $order['total_amount'] . '元';
                    Db::name('order')->where(['id' => $v['order_id']])->update(['pay_status' => 3, 'user_note' => $user_note]);


//                    $total_amount = $order['total_amount'];
//                    $user_data = [
//                        'account' => Db::raw("account+$total_amount")
//                    ];
//                    Db::name('user')->where(['id' => $v['follow_user_id']])->update($user_data);

                    //余额记录
                    $memo = '成团失败，退回' . $order['total_amount'] . '元';
                    change_user_account_log($this->user_id, $order['total_amount'], $memo, $order['order_sn'], $order['id']);

                    //写入资金记录表
                    change_expense($order['total_amount'],$order['id']);

                }
            }
        }
    }


//$this->isHasTeamFollow($found_id,$user_id);
//

    /**
     * 用户是否参与过该团
     * @param $found_id
     * @param $user_id
     * @return bool
     */
    public function isHasTeamFollow($found_id,$user_id){
//        $isHasTeamFollow = Db::name('team_follow')->where(['found_id' => $this])->count();
        $isFollow = Db::name('team_follow')->where(['found_id' => $found_id, 'follow_user_id' => $user_id])->count();

        $ifFound = Db::name('team_found')->where(['id' => $found_id, 'user_id' => $user_id])->count();
        if(($isFollow > 0) || ($ifFound > 0) ){
            return true;
        }else{
            return false;
        }
    }




}





